package com.imcrl.component.drager{

	import com.imcrl.component.drager.AbstractDragger;
	
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;
	
	import starling.display.Sprite;
	
	
	public class RejectedMotion implements IDropMotion{
			
		private var timer:Timer;
		private var initiatorPos:Point;
		private var dragProxy:Sprite;
		
		public function RejectedMotion(){
			timer = new Timer(40);
			timer.addEventListener(TimerEvent.TIMER, __enterFrame);
		}
		
		private function startNewMotion(dragInitiator:AbstractDragger, dragProxy : Sprite):void{
			this.dragProxy = dragProxy;
			initiatorPos = dragInitiator.getGlobalLocation();
			if(initiatorPos == null){
				initiatorPos = new Point();
			}
			timer.start();
		}
		
		public function forceStop():void{
			finishMotion();
		}
		
		public function startMotion(dragInitiator:AbstractDragger, dragProxy : Sprite) : void {
			startNewMotion(dragInitiator, dragProxy);
		}
		
		protected function finishMotion():void{
			if(timer.running){
				timer.stop();
				dragProxy.alpha = 1;
				if(dragProxy.parent != null){
					dragProxy.parent.removeChild(dragProxy);
				}
			}
		}
		
		private function __enterFrame(e:TimerEvent):void{
			//check first
			var speed:Number = 0.5;
			
			var p:Point = new Point(dragProxy.x, dragProxy.y);
			p = dragProxy.parent.localToGlobal(p);
			p.x += (initiatorPos.x - p.x) * speed;
			p.y += (initiatorPos.y - p.y) * speed;
			if(Point.distance(p, initiatorPos) < 2){
				finishMotion();
				return;
			}
			p = dragProxy.parent.globalToLocal(p);
			dragProxy.alpha += (0.04 - dragProxy.alpha) * speed;
			dragProxy.x = p.x;
			dragProxy.y = p.y;
		}
		
	}
}